<template>
  <!--size抽屉宽度（或高度）  default 378px 和 large 736px -->
  <a-drawer
      v-model:open="visible"
      ref="employeeDetailModalRef"
      class="edit-drawer modal-fixed-bottom"
      root-class-name="root-customer-drawer"
      width="800px"
      :closable="false"
      @close="onClose"
  >
    <div class="closeable" @click="onClose">{{ $t('self.closeButton') }}</div>
    <div class="modal-header">{{ title }}</div>
    <a-form :model="formState" :rules="formRules" :label-col="labelCol" :wrapper-col="wrapperCol"
            @finish="onSubmit"
    >
      <a-form-item :label="$t('self.operators.tips1')" name="orgName">
        <a-input allow-clear v-model:value="formState.orgName" placeholder="" />
      </a-form-item>
      <a-form-item :label="$t('self.operators.tips17')" name="phone">
        <a-input allow-clear v-model:value="formState.phone" placeholder="" />
      </a-form-item>
      
      <a-form-item :label="$t('self.operators.tips40')" name="country">
        <vue-country-code
          @onSelect="handleCountrySelect"
          type="name"  
          :preferred-countries="['cn', 'us', 'gb']"
          :placeholder="$t('self.pleaseChoose')"
          :search-placeholder="$t('self.searchCountry')"
          style="width: 100%;" 
        />
      </a-form-item>
      

      <a-form-item :label="$t('self.operators.tips43')" name="commissionType"
                   :rules="[{required: true, message: $t('self.pleaseSelect') + $t('self.operators.commissionType'), trigger: 'change'}]">
        <a-radio-group v-model:value="formState.commissionType" @change="handleCommissionTypeChange">
          <a-radio :value="'percentage'">{{ $t('self.operators.percentage') }}</a-radio>
          <a-radio :value="'flat'">{{ $t('self.operators.flatFee') }}</a-radio>
        </a-radio-group>
      </a-form-item>
      

      <a-form-item 
        v-if="formState.commissionType === 'percentage'"
        :label="$t('self.operators.tips41')" 
        name="commission"
        :rules="[{required: true, message: $t('self.pleaseInput') + $t('self.operators.tips41'), trigger: 'change'}]"
      >
        <a-input type="number" allow-clear v-model:value="formState.commission" placeholder="Percentage cost fee (%)" />
      </a-form-item>
      
      <a-form-item 
        v-if="formState.commissionType === 'flat'"
        :label="$t('self.operators.tips42')" 
        name="amount"
        :rules="[{required: true, message: $t('self.pleaseInput') + $t('self.operators.tips42'), trigger: 'change'}]"
      >
        <a-input  type="number"  allow-clear v-model:value="formState.amount" placeholder="Basis for flat fee" />
      </a-form-item>

      <div class="base-flex base-rows base-align-items-center base-justify-content-center footer">
        <a-button type="primary" html-type="submit">{{ $t('self.submitButton') }}</a-button>
        <a-button class="base-ml10" @click="onClose">{{ $t('self.cancelButton') }}</a-button>
      </div>

    </a-form>

  </a-drawer>
</template>

<script setup>
import { computed, getCurrentInstance, onMounted, ref } from 'vue'
import { message } from 'ant-design-vue'
import { VueCountryCode } from 'vue3-country-select'
import 'vue3-country-select/style.css'
import 'intl-tel-input/build/css/intlTelInput.css'
const { proxy } = getCurrentInstance()
const $TOOL = proxy.$TOOL
const $API = proxy.$API
const $T = proxy.$t
const emit = defineEmits(['close','ok'])

const visible = ref(false)
// 模式，add新增，show查看，edit编辑
const mode = ref('add')
const labelCol = {
  style: {
    width: '230px',
  },
};
const wrapperCol = {
  span: 16,
};
const title = ref('')
const formState = ref({
  orgName: '',
  phone: '',
  country: '',
  commissionType: '', // 新增：佣金类型，'percentage'表示百分比，'flat'表示固定费用
  commission: 0,      // 百分比佣金
  amount: 0           // 固定费用
})
const formRules = ref({
  orgName: [{required: true,message: $T('self.pleaseInput') + $T('self.operators.tips1'),trigger: 'change'}],
  phone: [{required: true,message: $T('self.pleaseInput') + $T('self.operators.tips2'),trigger: 'change'}],
})
const handleCountrySelect = (country) => {
  // country 结构：{ iso2: 'cn', name: 'China', dialCode: '86' }
  console.log(country)
  formState.value.country = country.name
  // formState.countryCode = country.iso2 
}
// 处理佣金类型变更
const handleCommissionTypeChange = (e) => {
  if (e.target.value === 'percentage') {
    formState.value.amount = 0;
  } else {
    formState.value.commission = 0;
  }
}

onMounted(() => {

})

const onSubmit = (values) => {
  const params = { ...formState.value }
  // 验证数字输入
  if (formState.value.commissionType === 'percentage' && 
      (values.commission == null || isNaN(values.commission) || values.commission < 0)) {
    message.error($T('self.operators.tips44'));
    return;
  }
  
  if (formState.value.commissionType === 'flat' && 
      (values.amount == null || isNaN(values.amount) || values.amount < 0)) {
    message.error($T('self.operators.invalidFlatFee'));
    return;
  }

  if(mode.value === 'add') {
    // 添加
    $API.backend.operators.add.post(params).then(res => {
      message.success($T('self.message.success'))
      onReset()
      visible.value = false
      emit('ok')
    }).catch(err => {
      message.error(err.msg);
    })
  } else {
    // 修改
    $API.backend.operators.edit.post(params).then(res => {
      message.success($T('self.message.success'))
      onReset()
      visible.value = false
      emit('ok')
    }).catch(err => {
      message.error(err.msg);
    })
  }
}

const onReset = () => {
  formState.value = {
    orgName: '',
    phone: '',
    country: '',
    commissionType: '',
    commission: 0,
    amount: 0
  }
}

const onClose = () => {
  onReset()
  visible.value = false
  emit('close')
}

const add = () => {
  mode.value = 'add'
  title.value = $T('self.operators.modal.title1')
  visible.value = true
}

const edit = (record) => {
  mode.value = 'edit'
  if (record.commission && record.commission > 0) {
    record.commissionType = 'percentage';
  } else if (record.amount && record.amount > 0) {
    record.commissionType = 'flat';
  } else {
    record.commissionType = '';
  }
  
  formState.value = { ...record };
  title.value = $T('self.operators.modal.title2') + '：' + formState.value.orgName
  visible.value = true
}


defineExpose({
  add,
  edit,
})
</script>

<style lang="scss" scoped>
.edit-drawer {
  position: relative;
  .closeable {
    @include closeable;
  }
}

.ant-radio-group {
  display: flex;
  gap: 20px;
}

:deep(.vue-country-code) {
  .vcc-input {
    border: 1px solid #d9d9d9;
    border-radius: 4px;
    height: 32px;
    padding: 4px 8px;
    width: 100%;   
  }
  
  .vcc-dropdown {
    border-radius: 4px;
    box-shadow: 0 2px 8px rgba(0, 0, 0, 0.15);
  }
}
:deep(.dropdown .dropdown-list){
  width: 100%;   
}
:deep(.dropdown .dropdown-list .dropdown-item){
  width: 100%;   
}
</style>
